package com.hserver.docker.controller;

import cn.hserver.plugin.web.annotation.Controller;
import cn.hserver.plugin.web.annotation.GET;
import cn.hserver.plugin.web.annotation.POST;
import cn.hserver.plugin.web.interfaces.HttpResponse;
import com.hserver.docker.bean.Registry;
import com.hserver.docker.config.ConstConfig;
import com.hserver.docker.service.RegistryService;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.server.util.JsonResult;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;


/**
 * @author hxm
 */
@Controller("/registry/")
public class RegistryController {

    @Autowired
    private RegistryService registryService;

    @GET("index")
    public void index(HttpResponse httpResponse) {
        Map<String, Object> map = new HashMap<>();
        List<String> data = registryService.data();
        if (data == null) {
            data = new ArrayList<>();
            map.put("init", "init");
        }
        map.put("data", data);
        httpResponse.sendTemplate("/registry/index.ftl", map);
    }

    @GET("init")
    public void init(HttpResponse httpResponse) {
        Map<String, Object> map = new HashMap<>();
        String host = "";
        try {
            if (ConstConfig.DOCKER_URL.startsWith("tcp")) {
                URL url = new URL(ConstConfig.DOCKER_URL.replace("tcp", "http"));
                host = url.getHost();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        map.put("host", host);
        httpResponse.sendTemplate("/registry/init.ftl", map);
    }

    @POST("create")
    public JsonResult create(Registry registry) {
        if (registry != null) {
            registry.setId(UUID.randomUUID().toString());
        } else {
            return JsonResult.error("异常");
        }
        if (registry.getHost() == null || registry.getHost().trim().length() < 1) {
            return JsonResult.error("Host不能为空");
        }
        if (registry.getPath() == null || registry.getPath().trim().length() < 1) {
            return JsonResult.error("Path不能为空");
        }
        registryService.add(registry);
        return JsonResult.ok();
    }

}
